package com.simple.mqtt.common.domain;

import java.util.*;

public class StrTemplateParser {

    private final List<String> literals = new ArrayList<>();
    private final List<String> variables = new ArrayList<>();

    public StrTemplateParser(String template) {
        parseTemplate(template);
    }

    private void parseTemplate(String template) {
        if (template == null || template.isEmpty()) {
            throw new IllegalArgumentException("模板字符串不能为空");
        }

        int start = 0;
        int length = template.length();

        while (start < length) {
            int varStart = template.indexOf("${", start);
            if (varStart == -1) {
                literals.add(template.substring(start));
                break;
            }

            literals.add(template.substring(start, varStart));
            int varIdx = varStart + 2;
            int varEnd = template.indexOf('}', varIdx);
            if (varEnd == -1) {
                throw new IllegalArgumentException("模板格式错误：缺少结束符 '}'");
            }
            if (varEnd == varIdx) {
                throw new IllegalArgumentException("模板格式错误：变量名为空");
            }

            variables.add(template.substring(varIdx, varEnd));
            start = varEnd + 1;
        }
    }

    public Map<String, String> getVariables(String input) {
        if (input == null || literals.isEmpty()) {
            return Collections.emptyMap();
        }

        Map<String, String> result = new LinkedHashMap<>(variables.size());
        int pos = 0;

        // 匹配第一个前缀
        String firstLiteral = literals.get(0);
        if (!input.startsWith(firstLiteral)) {
            return Collections.emptyMap();
        }
        pos += firstLiteral.length();

        for (int i = 0; i < variables.size(); i++) {
            String nextLiteral = literals.get(i + 1);
            String value;

            if (nextLiteral.isEmpty()) {
                value = input.substring(pos);
                pos = input.length();
            } else {
                int nextPos = input.indexOf(nextLiteral, pos);
                if (nextPos == -1) {
                    return Collections.emptyMap();
                }
                value = input.substring(pos, nextPos);
                pos = nextPos + nextLiteral.length();
            }

            result.put(variables.get(i), value);
        }

        return pos == input.length() ? result : Collections.emptyMap();
    }

    // 静态便捷方法
    public static Map<String, String> parseVariables(String template, String input) {
        return new StrTemplateParser(template).getVariables(input);
    }
}